package com.minelx.hellopandas.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.minelx.httpclient.core.Requests;
import com.minelx.httpclient.core.request.IResponse;
import com.minelx.sequence.common.Templates;
import io.gitee.minelx.commontools.Files;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import static com.alibaba.fastjson.serializer.SerializerFeature.PrettyFormat;

public class PandasChief {

	private static final int CONNECT_TIMEOUT = 120 /* MINUTES */ * 60 * 1000;

	private final String host;

	private final int port;

	private PandasChief(String host, int port) {
		this.host = host;
		this.port = port;
	}

	DataFrameDescription doRequest(String method, JSONObject params) {
		Templates templates = new Templates(Files.toString("/requests/post_execution.request"));
		Map<String, String> parameters = new HashMap<>();
		parameters.put("host", host);
		parameters.put("port", String.valueOf(port));
		parameters.put("methodName", method);
		parameters.put("params", params.toJSONString());
		IResponse response = Requests.parse(templates.render(parameters)).fetch(CONNECT_TIMEOUT);
		JSONObject responseBody = JSON.parseObject(response.contentAsText(StandardCharsets.UTF_8));
		if (!responseBody.getBooleanValue("success")) {
			throw new IllegalStateException(
					"error while requesting pandas execution of " + method + ", \n" +
							"params: " + params.toString(PrettyFormat) + ", \n" +
							"error message: " + responseBody.getString("message"));
		}
		// if successfully requested, we will receive a description of destination
		return DataFrameDescription.from(responseBody.getJSONObject("data").getJSONObject("destinationDescription"));
	}

	public static PandasChief at(String host, int port) {
//		return new PandasChief("127.0.0.1", 5001);
		return new PandasChief(host, port);
	}
}
